package com.tintintech.sendmail;


import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.tintintech.sendmail.helper.DataHelper;
import com.tintintech.sendmail.util.MailStat;

public final class PutMailboxTask {

	private static final ScheduledThreadPoolExecutor TimerWorker = new ScheduledThreadPoolExecutor(2);
	
	private static final int taskDelay  = new Integer(Config.GLOBALS.get("taskDelay")).intValue();
	private static final int taskPeriod = new Integer(Config.GLOBALS.get("taskPeriod")).intValue(); 

	public static void start()
	{
		handleSenderTask();
		handleStatisticsTask();
		processedTask(); //阻塞的
	}
	
	private static void handleSenderTask()
	{
		TimerWorker.scheduleAtFixedRate(new Thread(){
			public void run(){
		        try {
		        	if (MailStat.MAILBOX_LOAD_DATA.get() == false)
		        	{
//		        		DataHelper.DB.loadData();
		        		DataHelper.DB.load();
		        	}
		        	/*
		            if (MailService.getInstance().getRunning() == false)
		            {
		            	MailService.getInstance().setRunning(true);
//		            	MailService.getInstance().startWorker();
		            	MailService.getInstance().run();
		            }
		            */
		        } catch (Exception e) {
		        	System.out.println("put mailbox failed");
		        	e.printStackTrace();//有可能会抛空指针异常
		        }
			}
		}, taskDelay, taskPeriod, TimeUnit.MILLISECONDS);
	}
	
	private static void handleStatisticsTask()
	{
		TimerWorker.scheduleAtFixedRate(new Thread(){
			public void run(){
				MailStat.sync();
			}
		}, taskDelay * 20, taskPeriod * 5, TimeUnit.MILLISECONDS);
	}
	
	private static void processedTask()
	{
		new Thread(){
			
			public void run(){
				Processor.getInstance().startWorker();
			}
		}.start();
	}
}
